package one.three.web.five;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class StackMax {

	private Node<Integer> first;
	private int n;
	private int max = Integer.MIN_VALUE;

	public StackMax() {
		first = null;
		n = 0;
	}

	public boolean isEmpty() {
		return first == null;
	}

	public int size() {
		return n;
	}

	public void push(Integer item) {
		Node oldfirst = first;
		first = new Node();
		first.item = item;
		first.next = oldfirst;
		n++;
		uploadMax();
	}

	public Integer pop() {
		if (isEmpty()) {
			throw new NoSuchElementException("Stack underflow");
		}
		Integer item = first.item;
		first = first.next;
		n--;
		uploadMax();
		return item;
	}

	private void uploadMax() {
		max = Integer.MIN_VALUE;
		Node<Integer> c = first;
		int e;
		while (c != null) {
			e = c.item;
			if (e > max)
				max = e;
			c = c.next;
		}
	}

	public int getMax() {
		return max;
	}

	private class Node<Item> {
		Item item;
		Node<Item> next;
	}

	private class LinkedIterator<Item> implements Iterator<Item> {
		private Node<Item> current;

		public LinkedIterator(Node<Item> first) {
			this.current = first;
		}

		@Override
		public boolean hasNext() {

			return current != null;
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}

		@Override
		public Item next() {
			if (!hasNext()) {
				throw new NoSuchElementException();
			}
			Item item = current.item;
			current = current.next;
			return item;
		}

	}

	public static void main(String[] args) throws Exception {

		StackMax s = new StackMax();
		s.push(1);
		s.push(2);
		s.push(3);

		System.out.println(s.pop());
		System.out.println(s.getMax());
		// System.out.println(s.pop());
	}
}
